#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "../comm/util.hpp"
#include "../comm/Log.hpp"

namespace ns_runner
{
    using namespace ns_util;
    class Runner
    {
    public:
        static int Run(const std::string &filename, int cpu_limit, int mem_limit)
        {
            std::string execute = PathUtil::Exe(filename);

            std::string stdin = PathUtil::Stdin(filename);
            std::string stdout = PathUtil::Stdout(filename);
            std::string stderr = PathUtil::Stderr(filename);

            // 打开三个文件
            umask(0);
            int in_fd = open(stdin.c_str(), O_CREAT | O_WRONLY, 0644);
            int out_fd = open(stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int err_fd = open(stderr.c_str(), O_CREAT | O_WRONLY, 0644);

            if (in_fd < 0 || out_fd < 0 || err_fd < 0)
            {
                LOG(ERROR, "open std file error");
                return -1;
            }

            pid_t id = fork();
            if (id < 0)
            {
                close(in_fd);
                close(out_fd);
                close(err_fd);
                LOG(ERROR, "run fork error");
                return -1;
            }
            else if (id == 0)
            {
                // child
                dup2(in_fd, 0);
                dup2(out_fd, 1);
                dup2(err_fd, 2);
                // 对cpu和内存资源进行限制
                SetProcLimit(cpu_limit, mem_limit);
                execl(execute.c_str(), execute.c_str(), nullptr);
                // 程序替换失败
                exit(1);
            }
            // father
            int status = 0;
            int ret = waitpid(id, &status, 0);
            close(in_fd);
            close(out_fd);
            close(err_fd);
            int sig = 0; // 检验是否是被信号所杀
            if (ret > 0)
            {
                if (WIFEXITED(status))
                {
                    // 正常退出
                    int exit_code = WEXITSTATUS(status);
                    if (exit_code == 0)
                    {
                        LOG(INFO, "run success");
                    }
                    else if (exit_code == 1)
                    {
                        LOG(ERROR, "run execlp fail");
                        return -1;
                    }
                    else
                    {
                        LOG(ERROR, "unknow status code:" + std::to_string(exit_code));
                        return -1;
                    }
                }
                else
                {
                    // 异常退出
                    sig = status & 0x7f;
                    LOG(WARNING, "sig: " + std::to_string(sig));
                }
            }
            else
            {
                // 等待失败
                LOG(ERROR, "run wait fail");
                return -1;
            }
            return sig; // 返回收到的信号 正常是0 异常时一个信号
        }

    private:
        static void SetProcLimit(int cpu_limit, int mem_limit)
        {
            struct rlimit climit;
            climit.rlim_cur = cpu_limit;
            climit.rlim_max = RLIM_INFINITY;

            setrlimit(RLIMIT_CPU, &climit);

            struct rlimit mlimit;
            mlimit.rlim_cur = mem_limit * 1024; // 转为kb
            mlimit.rlim_max = RLIM_INFINITY;

            setrlimit(RLIMIT_AS, &mlimit);
        }
    };
}
